package com.ym.core.shiro.realm;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.ym.common.constant.UserDetails;
import com.ym.core.exception.SysLoginException;
import com.ym.core.shiro.service.SysLoginService;
import com.ym.core.shiro.token.SysToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;


/**
 * 自定义权限匹配和账号密码匹配
 */
@Slf4j
public class SystemShiroRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

    /**
     * 主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        SimpleAuthenticationInfo authenticationInfo = null;
        SysToken sysToken = (SysToken) token;
        UserDetails userDetails = SpringUtil.getBean(SysLoginService.class).loginByUsernamePassword(sysToken);
        if (null == userDetails) {
            return null;
        }

        authenticationInfo = new SimpleAuthenticationInfo(
                userDetails,
                userDetails.getPassword(),
                ByteSource.Util.bytes(userDetails.getSalt()),
                getName()
        );
        return authenticationInfo;
    }


    @Override
    public boolean supports(AuthenticationToken token) {
        if (token instanceof SysToken) {
            return true;
        }
        return false;
    }
}
